<script setup>
import { useRouter } from 'vue-router';
import authService from "@/services/auth.service";
import { useAuthStore } from '@/stores/auth';
import { ElMessage, ElForm, ElFormItem, ElInput, ElButton, ElCheckbox, ElDatePicker } from 'element-plus';
import { CircleCheck, Lock, User } from '@element-plus/icons-vue';
import { onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { AxiosError } from 'axios';
import { Search, Refresh, Plus, Edit, Delete, View, Upload, Download, Share, Close, Message, Phone } from "@element-plus/icons-vue";
import { REGEX_EMAIL, REGEX_PASSWORD, REGEX_PHONE } from "@/utils/regexes";

const router = useRouter();

const entity = ref({});
const rememberMe = ref(true);
const formRef = ref();
const loading = ref(false);
const verifyCodeUrl = ref("");

const rules = reactive({
    username: [
        {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
        },
        {
            trigger: 'blur',
            asyncValidator: (rule, value, callback) => {
                if (!value) {
                    return callback();
                }
                return authService.checkUsername(value).then((res) => {
                    if (!Boolean(res.data.data)) {
                        callback(new Error("用户名已存在"));
                    } else {
                        callback();
                    }
                }).catch(err => {
                    callback(new Error(err.response?.data?.message || err.message));
                });
            }
        }
    ],
    password: [
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error("请输入密码"));
                } else if (!REGEX_PASSWORD.test(value)) {
                    callback(
                        new Error("密码格式应为8-18位数字、字母、符号的任意两种组合")
                    );
                } else {
                    callback();
                }
            },
            trigger: "blur"
        }
    ],
    confirmPassword: [
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error("请输入确认密码"));
                } else if (entity.value.password && entity.value.confirmPassword && entity.value.password != entity.value.confirmPassword) {
                    callback(new Error("两次密码输入不一致"));
                } else {
                    callback();
                }
            },
            trigger: "blur"
        }
    ],
    phone: [
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error("请输入手机号"));
                } else if (!REGEX_PHONE.test(value)) {
                    callback(new Error("手机号格式不正确"));
                } else {
                    callback();
                }
            },
            trigger: "blur"
        },
        {
            trigger: 'blur',
            asyncValidator: (rule, value, callback) => {
                if (!value) {
                    return callback();
                }
                return authService.checkPhone(value).then((res) => {
                    if (!Boolean(res.data.data)) {
                        callback(new Error("手机号已存在"));
                    } else {
                        callback();
                    }
                }).catch(err => {
                    callback(new Error(err.response?.data?.message || err.message));
                });
            }
        }
    ],
    email: [
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error("请输入邮箱"));
                } else if (!REGEX_EMAIL.test(value)) {
                    callback(new Error("邮箱格式不正确"));
                } else {
                    callback();
                }
            },
            trigger: "blur"
        },
        {
            trigger: 'blur',
            asyncValidator: (rule, value, callback) => {
                if (!value) {
                    return callback();
                }
                return authService.checkEmail(value).then((res) => {
                    if (!Boolean(res.data.data)) {
                        callback(new Error("邮箱已存在"));
                    } else {
                        callback();
                    }
                }).catch(err => {
                    callback(new Error(err.response?.data?.message || err.message));
                });
            }
        }
    ],
    verifyCode: [
        {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
        },
    ],
});

const register = async () => {
    const formEl = formRef.value;
    loading.value = true;
    if (!formEl) {
        loading.value = false;
        return;
    }
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            try {
                const res = await authService.register(entity.value);
                ElMessage({ message: "注册成功", type: "success" });
                router.push("/login");
            } catch (err) {
                if (err instanceof AxiosError) {
                    const msg = err.response?.data?.message || err.message;
                    ElMessage({ message: msg, type: "error" });
                }
                updateVerifyCode();
                throw err;
            } finally {
                loading.value = false;
            }
        } else {
            loading.value = false;
            return fields;
        }
    });
};

const login = () => {
    router.push("/login");
}

const updateVerifyCode = async () => {
    const res = await authService.getVerifyCode();
    verifyCodeUrl.value = `${res.data.data?.image}`;
    entity.value.verifyCodeKey = res.data.data?.key;
}

const load = async () => {
}

onMounted(async () => {
    updateVerifyCode();

    load();
});

</script>

<template>
    <div class="register-container">
        <div class="register-box">
            <ElForm class="register-form" ref="formRef" :model="entity" :rules="rules" size="large">
                <h3 class="text-center">注册新用户</h3>
                <ElFormItem prop="username">
                    <ElInput clearable v-model="entity.username" placeholder="用户名/手机号/邮箱" :prefix-icon="User" />
                </ElFormItem>

                <ElFormItem prop="password">
                    <ElInput clearable show-password v-model="entity.password" placeholder="密码" :prefix-icon="Lock" />
                </ElFormItem>

                <ElFormItem prop="confirmPassword">
                    <ElInput clearable show-password v-model="entity.confirmPassword" placeholder="确认密码"
                        :prefix-icon="Lock" />
                </ElFormItem>

                <ElFormItem prop="email">
                    <ElInput v-model="entity.email" placeholder="邮箱" :prefix-icon="Message"></ElInput>
                </ElFormItem>

                <ElFormItem prop="phone">
                    <ElInput v-model="entity.phone" placeholder="手机号" :prefix-icon="Phone"></ElInput>
                </ElFormItem>

                <ElFormItem class="verify-code-row" prop="verifyCode">
                    <ElInput clearable v-model="entity.verifyCode" placeholder="验证码" :prefix-icon="CircleCheck">
                        <template #append>
                            <img :src="verifyCodeUrl" class="verify-code" @click="updateVerifyCode()" />
                        </template>
                    </ElInput>
                </ElFormItem>

                <ElFormItem>
                    <div class="w-full">
                        <ElButton class="w-full" size="default" type="primary" :loading="loading" @click="register()">
                            注册
                        </ElButton>
                    </div>
                    <div class="w-full">
                        <ElButton class="w-full" size="default" @click="login()">
                            已有账号，返回登录
                        </ElButton>
                    </div>
                </ElFormItem>
            </ElForm>
        </div>
    </div>
</template>

<style lang="scss">
.register-bg {
    position: fixed;
    height: 100%;
    left: 0;
    bottom: 0;
    z-index: -1;
}

.register-container {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    position: absolute;
    display: flex;
    justify-items: center;
    justify-content: center;

    .register-box {
        display: flex;
        align-items: center;
        text-align: center;

        .register-form {
            width: 360px;

            .verify-code-row {
                .el-input-group__append {
                    padding: 0;
                }

                .verify-code {
                    height: 40px;
                }
            }

            .link-forget-password {
                color: var(--el-color-primary);
                cursor: pointer;
            }
        }
    }
}
</style>